我們來看到C#要如何計算程式碼的執行時間呢 ~
有兩種方法分別是 Stopwatch DateTime ~
學習目標: 計算程式碼執行時間的實務
學習難度: ☆☆☆
Stopwatch (StartNew and Stop)
using System;
using System.Diagnostics;
namespace ConsoleApp1
{
class MainProgram
{
static void Main()
{
var stopWatch = Stopwatch.StartNew(); //啟動Stopwatch
for (int i = 0; i < 1000; i++)
{
Console.WriteLine("123"+"\n");
}
stopWatch.Stop(); //停止Stopwatch
Console.WriteLine(stopWatch.ElapsedMilliseconds); //印出執行時間(毫秒)
}
}
}
Stopwatch (GetTimestamp)
using System;
using System.Diagnostics;
namespace ConsoleApp1
{
class MainProgram
{
static void Main()
{
var start = Stopwatch.GetTimestamp(); //紀錄時間(起點)
for (int i = 0; i < 1000; i++)
{
Console.WriteLine("123"+"\n");
}
var end = Stopwatch.GetTimestamp(); //紀錄時間(終點)
Console.WriteLine(end-start); //印出執行時間(毫秒)
}
}
}
DateTime
using System;
namespace ConsoleApp1
{
class MainProgram
{
static void Main()
{
DateTime start = DateTime.Now; //紀錄時間(起點)
for (int i = 0; i < 1000; i++)
{
Console.WriteLine("123"+"\n");
}
DateTime end = DateTime.Now; //紀錄時間(終點)
TimeSpan timeSpan = (end - start);
Console.WriteLine(timeSpan.TotalMilliseconds); //印出執行時間(毫秒)
}
}
}
參考資料:
https://www.geeksforgeeks.org/how-to-calculate-the-code-execution-time-in-c-sharp/